﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SG.Sys.Console.CommandProcessing;
using SG.Sys.Console.Process;

namespace SG.Sys.Console.Implementation
{
    public class SimpleRepl : IProcessWrapper
    {
        public void SendClose()
        {
            
        }

        public event EventHandler<LineOutputEvent> OnOutput;

        public char PromptChar { get { return '$'; } }

        public string Title { get; private set; }

        private int _id;
        public int ID
        {
            get { return _id > 0 ? _id : (_id = ProcessWrapperBase.GetUniqueID(GetType())); }
        }

        public string Name
        {
            get { return string.Format("[{0:d}]", ID); }
        }

        public void Start()
        {
            // TODO setup environment
        }

        public StateChange SendCommand(Entry entry)
        {
            var exe = entry.Command.Executable.ToLowerInvariant();
            var args = entry.Command.Arguments;

            switch (exe)
            {
                case "echo":
                    OnOutput(this, new LineOutputEvent(args.FirstOrDefault(), OutputKind.Output, false, 1));
                    break;
            }

            return StateChange.None;
        }

        public Command ParseCommand(string cmdLine)
        {
            cmdLine = cmdLine.Trim();
            var firstSpace = cmdLine.IndexOf(' ');

            string objectRef;
            var arguments = new List<string>();
            if (firstSpace > 0)
            {
                objectRef = cmdLine.Substring(0, firstSpace);
                var rest = cmdLine.Substring(firstSpace).TrimStart();

                if (rest.Length > 0)
                {
                    arguments.AddRange(rest.Split(' '));
                }
            }
            else
            {
                objectRef = cmdLine;
            }
            return new Command(cmdLine, objectRef, arguments);
        }
    }
}
